package org.witsoft.demo.graphql.resovler;

import graphql.kickstart.execution.context.GraphQLContext;
import graphql.kickstart.tools.GraphQLResolver;
import graphql.schema.DataFetcher;
import graphql.schema.DataFetchingEnvironment;
import lombok.RequiredArgsConstructor;
import org.dataloader.DataLoader;
import org.dataloader.DataLoaderRegistry;
import org.springframework.stereotype.Component;
import org.witsoft.demo.graphql.entity.Author;
import org.witsoft.demo.graphql.entity.Book;
import org.witsoft.demo.graphql.enums.CountryEnum;
import org.witsoft.demo.graphql.repository.AuthorRepository;

import java.util.Optional;
import java.util.concurrent.CompletableFuture;

@Component
@RequiredArgsConstructor
public class BookResolver implements GraphQLResolver<Book> {

    private final AuthorRepository authorRepository;

    private final DataLoader<Long, Author> authorDataLoader;

//    public Optional<Author> getAuthor(Book book) {
//        return authorRepository.findById(book.getAuthorId());
//    }

    /**
     * 解决n + 1查询问题
     * @param book
     * @return
     */
    public CompletableFuture<Author> getAuthor(Book book) {
        return authorDataLoader.load(book.getAuthorId());
    }


    public String getPrice(Book book, CountryEnum country){
        if (country == CountryEnum.CHINA) {
            return "¥" + Math.round(book.getPrice() * 6);
        } else if (country == CountryEnum.USA) {
            return "$" + book.getPrice();
        } else {
            return "free";
        }
    }
}